package com.lt.tccdemo.service;

import com.lt.tccdemo.db108.dao.AccountAMapper;
import com.lt.tccdemo.db108.model.AccountA;
import com.lt.tccdemo.db109.dao.AccountBMapper;
import com.lt.tccdemo.db109.model.AccountB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @author lucine
 * @version 1.0 2021/10/4 20:47
 */
@Service
public class AccountService {

    @Autowired
    private AccountAMapper accountAMapper;

    @Autowired
    private AccountBMapper accountBMapper;


    @Transactional(transactionManager = "xm108",rollbackFor = Exception.class)
    public void transferAccount(){
        System.out.println("aaaaaaa进入了");
//        AccountA accountA = accountAMapper.selectByPrimaryKey(1);
//        //扣减余额200
//        accountA.setBalance(accountA.getBalance().subtract(new BigDecimal(200)));
//        int i = accountAMapper.updateByPrimaryKey(accountA);
//
//
//        AccountB accountB = accountBMapper.selectByPrimaryKey(2);
//        //加余额200
//        accountB.setBalance(accountB.getBalance().add(new BigDecimal(200)));
//        i = accountBMapper.updateByPrimaryKey(accountB);
//        int b = 1/0;
        //================ 出现上述问题时，是不能保证一致性的
        AccountA accountA = accountAMapper.selectByPrimaryKey(1);
        //扣减余额200
        accountA.setBalance(accountA.getBalance().subtract(new BigDecimal(200)));
        int i = accountAMapper.updateByPrimaryKey(accountA);


        AccountB accountB = accountBMapper.selectByPrimaryKey(2);
        //加余额200
        accountB.setBalance(accountB.getBalance().add(new BigDecimal(200)));
        i = accountBMapper.updateByPrimaryKey(accountB);

        //如果出现异常就扣减之前加上的200
        try {
            int b = 1/0;
        }catch (Exception e){
            accountB = accountBMapper.selectByPrimaryKey(2);
            ///扣减200
            accountB.setBalance(accountB.getBalance().subtract(new BigDecimal(200)));
            i = accountBMapper.updateByPrimaryKey(accountB);
            //抛出后 A数据源的会回滚
            throw  e;
        }

    }


}
